// challenge.js - 挑战关卡页面的核心逻辑
const util = require('../../../utils/util.js');
const { categoryConfig } = require('../../../utils/categoryConfig.js');

// 从App实例获取全局的challengeDataManager
const app = getApp();
const challengeDataManager = app.getChallengeDataManager();
const storageManager = app.getStorageManager();

Page({
  data: {
    totalChallenges: 0,
    winRate: 0,
    totalCoins: 0, // 默认值设为0，确保始终有数值
    recentRecords: [],
    recentGames: [],
    isLoading: true,
    categories: [],
    showTopicModal: false
  },

  onLoad: function() {
    // 加载用户挑战数据
    this.loadChallengeData();
  },

  onShow: function() {
    // 每次显示页面时重新加载数据
    this.loadChallengeData();
  },

  // 加载挑战数据
  loadChallengeData: function() {
    this.setData({ isLoading: true });
    
    // 模拟加载时间
    setTimeout(() => {
      // 从本地存储获取挑战统计数据
      const stats = challengeDataManager.getChallengeStats();
      
      // 获取最近的挑战记录
      let recentRecords = challengeDataManager.getRecentChallengeRecords(3);
      
      // 格式化日期
      recentRecords = recentRecords.map(record => ({
        ...record,
        date: util.formatTime(new Date(record.date))
      }));
      
      // 如果没有记录，初始化一些示例数据
      if (recentRecords.length === 0) {
        this._initializeSampleRecords();
        recentRecords = challengeDataManager.getRecentChallengeRecords(3).map(record => ({
          ...record,
          date: util.formatTime(new Date(record.date))
        }));
      }
      
      // 获取最近的游戏记录
      let recentGames = storageManager.getStorage(storageManager.STORAGE_KEYS.RECENT_WORD_GAMES) || [];
      
      // 格式化时间
      recentGames = recentGames.map(game => ({
        ...game,
        time: util.formatTime(new Date(game.timestamp))
      }));
      
      // 只显示最近5条记录
      recentGames = recentGames.slice(0, 5);
      
      // 获取魔法币数量 - 使用全局实例
      const app = getApp();
      const magicCoinManager = app.getMagicCoinManager();
      let totalCoins = magicCoinManager.getMagicCoins();
      
      // 确保totalCoins始终是有效的数值
      totalCoins = (typeof totalCoins === 'number' && !isNaN(totalCoins)) ? totalCoins : 0;
      
      this.setData({
        totalChallenges: stats.totalChallenges,
        winRate: stats.winRate,
        totalCoins: totalCoins,
        recentRecords: recentRecords,
        recentGames: recentGames,
        categories: categoryConfig,
        isLoading: false
      });
    }, 800);
  },
  
  // 初始化示例挑战记录
  _initializeSampleRecords: function() {
  },

  // 开始限时挑战
  startTimedChallenge: function() {
    wx.navigateTo({
      url: '/pages/challenge/timed-challenge/timed-challenge'
    });
  },

  // 开始主题挑战
  startTopicChallenge: function() {
    // 创建一个与challenge.wxml中分类主题样式相似的自定义弹窗
    this.setData({
      showTopicModal: true
    });
  },
  
  // 开始单词听写
  startWordDictation: function() {
    wx.navigateTo({
      url: '/pages/challenge/word-dictation/word-dictation'
    });
  },

  // 开始单词游戏
  startWordGames: function() {
    wx.navigateTo({
      url: '/pages/challenge/word-games/word-games'
    });
  },
  
  // 关闭主题选择模态框
  closeTopicModal: function() {
    this.setData({
      showTopicModal: false
    });
  },
  
  // 阻止模态框内容区域点击事件冒泡
  catchTap: function() {
    // 空函数，仅用于阻止冒泡
  },
  
  // 在主题模态框中选择特定主题
  selectTopicFromModal: function(e) {
    const category = e.currentTarget.dataset.category;
    const categoryItem = this.data.categories.find(item => item.category === category);
    
    if (categoryItem) {
      this.closeTopicModal();
      this.navigateToTopicChallenge(category, categoryItem.name);
    }
  },

  // 选择特定主题
  selectTopic: function(e) {
    const category = e.currentTarget.dataset.category;
    const categoryItem = this.data.categories.find(item => item.category === category);
    
    if (categoryItem) {
      this.navigateToTopicChallenge(category, categoryItem.name);
    }
  },

  // 跳转到主题挑战页面
  navigateToTopicChallenge: function(topic, topicName) {
    wx.navigateTo({
      url: `/pages/challenge/topic-challenge/topic-challenge?topic=${topic}&topicName=${topicName}`
    });
  },



  // 查看详细统计
  viewDetailedStats: function() {
    wx.navigateTo({
      url: '/pages/challenge/stats'
    });
  },

  // 下拉刷新
  onPullDownRefresh: function() {
    this.loadChallengeData();
    wx.stopPullDownRefresh();
  },

  // 分享页面
  onShareAppMessage: function() {
    return {
      title: '来和我一起挑战单词关卡吧！',
      path: '/pages/challenge/challenge',
      // imageUrl: '/images/challenge.png'
    };
  },
  
  // 分享到朋友圈
  onShareTimeline: function() {
    return {
      title: '来和我一起挑战单词关卡吧！',
      query: 'from=timeline',
      // imageUrl: '/images/challenge.png'
    };
  }
});